import random
import datetime


def shopping_system():
    """
    一个集成了V1.0和V2.0需求的超市购物系统。
    """
    # --- 数据初始化 (购前) ---

    # 1. 用户的初始资金 [cite: 9]
    money = 1000.0

    # 2. 商场内的商品列表 [cite: 10]
    products = [
        {"name": "方便面", "price": 5.5},
        {"name": "火腿肠", "price": 2.5},
        {"name": "矿泉水", "price": 2.0},
        {"name": "空调", "price": 1999.0},
        {"name": "笔记本电脑", "price": 4999.0},
        {"name": "T恤", "price": 88.0}
    ]

    # 3. 用户的空购物车 [cite: 4, 11]
    shopping_cart = []

    # --- V2.0: 抽取优惠券 ---
    coupons = [
        {"item": "空调", "discount": 0.8, "desc": "空调8折优惠券"},
        {"item": "T恤", "discount": 0.9, "desc": "T恤9折优惠券"},
        {"item": "方便面", "discount": 0.5, "desc": "方便面5折优惠券"},
        {"item": "无", "discount": 1.0, "desc": "谢谢惠顾"},
        {"item": "无", "discount": 1.0, "desc": "谢谢惠顾"}
    ]

    print("欢迎光临！您可以在我们10张优惠券中随机抽取一张。")
    # 为了模拟10张券，我们创建一个包含更多“谢谢惠顾”的券池
    coupon_pool = coupons * 2
    drawn_coupon = random.choice(coupon_pool)  #
    print(f"🎉 恭喜您，抽中了: 【{drawn_coupon['desc']}】")
    print("-" * 30)

    # --- 开始购物 (购中) ---
    while True:
        # 显示商品列表
        print("本店在售商品如下:")
        for i, product in enumerate(products):
            print(f"  编号: {i}, 名称: {product['name']}, 价格: {product['price']:.2f} 元")

        print("\n您可以：")
        print("  - 输入商品【编号】进行购买。")
        print("  - 输入【t】或【T】办理退货。 ")
        print("  - 输入【q】或【Q】退出并结算。 [cite: 25]")

        choice = input("请输入您的选择: ").strip()

        # A. 退出结算
        if choice.lower() == 'q':
            break

        # B. 办理退货
        elif choice.lower() == 't':
            if not shopping_cart:
                print("\n您的购物车是空的，无法办理退货。\n")
                continue

            print("\n--- 办理退货 ---")
            print("您购物车中的商品有:")
            for i, item in enumerate(shopping_cart):
                print(f"  编号: {i}, 名称: {item['name']}, 购买价格: {item['paid_price']:.2f} 元")

            try:
                return_choice = input("请输入您想退货的商品编号 (输入其他则放弃退货): ").strip()
                return_index = int(return_choice)

                if 0 <= return_index < len(shopping_cart):
                    # 从购物车中移除商品
                    returned_item = shopping_cart.pop(return_index)
                    # 返还金额
                    money += returned_item['paid_price']
                    print(f"\n✅ 商品【{returned_item['name']}】已成功退回！")
                    print(f"✅ 退款 {returned_item['paid_price']:.2f} 元已存入您的账户，当前余额: {money:.2f} 元。\n")
                else:
                    print("\n无效的编号，放弃退货。\n")
            except ValueError:
                print("\n输入无效，放弃退货。\n")
            continue

        # C. 添加商品到购物车
        try:
            choice_index = int(choice)
            if not (0 <= choice_index < len(products)):
                print("\n❌ 没有这个商品，别瞎弄！\n")  # [cite: 23]
                continue

            chosen_product = products[choice_index]
            product_price = chosen_product['price']

            # V2.0: 检查优惠券是否适用
            if chosen_product['name'] == drawn_coupon['item']:
                final_price = product_price * drawn_coupon['discount']
                print(
                    f"✨ 已为您使用【{drawn_coupon['desc']}】，商品【{chosen_product['name']}】价格从 {product_price:.2f} 元优惠至 {final_price:.2f} 元。")
            else:
                final_price = product_price

            # 检查钱是否足够 [cite: 15]
            if money >= final_price:  # [cite: 16]
                # 钱够，执行购买
                money -= final_price  # [cite: 18]
                # 添加到购物车，记录商品信息和实际支付价格
                shopping_cart.append({
                    "name": chosen_product['name'],
                    "original_price": product_price,
                    "paid_price": final_price
                })  # [cite: 17]
                print(f"\n✅ 恭喜，购买成功！【{chosen_product['name']}】已添加到您的购物车。")
                print(f"💰 您的卡余额还剩 {money:.2f} 元。\n")  # [cite: 19]
            else:
                # 钱不够
                print(f"\n❌ 钱不够！您的余额({money:.2f})不足以购买价格为 {final_price:.2f} 元的商品。请到其他超市购买！\n")  # [cite: 21]

        except ValueError:
            print("\n❌ 输入无效，请输入正确的商品编号、t或q。\n")

    # --- 打印购物小条 (购后) ---
    print("\n" + "=" * 40)
    print("          欢迎下次光临！")
    print("=" * 40)
    print("          您的购物小条          ")  # [cite: 6, 26]

    if not shopping_cart:
        print("\n您没有购买任何商品。")
    else:
        # V2.0: 人性化打印
        total_value = 0.0
        print(f"购物时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")  # [cite: 31]
        print("-" * 40)
        print(f"{'商品名称':<10}{'原价':>10}{'实付价':>10}")
        for item in shopping_cart:
            print(f"{item['name']:<10}{item['original_price']:>10.2f}{item['paid_price']:>10.2f}")
            total_value += item['paid_price']
        print("-" * 40)
        print(f"购物数量: {len(shopping_cart)} 件")  # [cite: 31]
        print(f"购买总价值: {total_value:.2f} 元")  # [cite: 31]

    print(f"卡上余额: {money:.2f} 元")  # [cite: 31]
    print("=" * 40)


# --- 运行购物系统 ---
if __name__ == "__main__":
    shopping_system()